package com.xtsoft.platform.globe.utils;


import java.util.ArrayList;
import java.util.List;

import com.xtsoft.platform.globe.interfaces.CommonUser;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.util.Assert;


/**
 * @Description TODO
 * @Param null
 * @return
 * @Author defencez
 * @Date 2024-04-21 10:42
*/
public final class SecurityUtils {

    private SecurityUtils() {
    }

    /**
     * @Description 获取当前登录用户
     * @Param
     * @return com.xtsoft.platform.globe.interfaces.CommonUser
     * @Author defencez
     * @Date 2024-04-21 11:22
    */
    public static CommonUser<?> getLoginedUser() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        Assert.notNull(authentication,"当前无认证用户");

            if (authentication.getPrincipal() instanceof CommonUser) {
            	return  (CommonUser<?>) authentication.getPrincipal();
            }
        return null;
    }


    /**
     * @Description 判断当前登录用户是否拥有某角色
     * @Param authority
     * @return boolean
     * @Author defencez
     * @Date 2024-04-21 11:23
    */
    public static boolean isCurrentUserInRole(String authority) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null) {
            return authentication.getAuthorities().stream()
                .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority));
        }
        return false;
    }
    

    /**
     * @Description 判断某用户是否在线
     * @Param sessionRegistry
     * @Param user
     * @return java.lang.Boolean
     * @Author defencez
     * @Date 2024-04-21 11:24
    */
    public static Boolean isLogined(SessionRegistry sessionRegistry,CommonUser<?> user) {

        Assert.notNull(user,"指定的用户不允许为空");

    	List<Object>  objs = sessionRegistry.getAllPrincipals();
		if(null != objs){
			for(Object obj: objs){
                if( obj instanceof CommonUser<?>)
				if(((CommonUser)obj).equals(user)){
					return true;
				}
			}
		}
		return false;
    }    

    /**
     * @Description 返回指定用户的所有Session列表，包括超期Session
     * @Param sessionRegistry
     * @Param loginId
     * @return java.util.List<org.springframework.security.core.session.SessionInformation>
     * @Author defencez
     * @Date 2024-04-21 11:29
    */
    public static List<SessionInformation> getLoginedSessions(SessionRegistry sessionRegistry,CommonUser<?> user) {
        Assert.notNull(user,"指定的用户不允许为空");
        List<Object>  objs = sessionRegistry.getAllPrincipals();
		List<SessionInformation> sessInfs = new ArrayList<SessionInformation>();
		
		if(null != objs && objs.size()>0){
			for(Object obj: objs){
                if(!(obj instanceof CommonUser<?>))
                    continue;

				if(((CommonUser<?>)obj).equals(user)){
					//包括该用户的超期会话
					if(null != sessionRegistry.getAllSessions(obj, true))
						sessInfs.addAll(sessionRegistry.getAllSessions(obj, true));
				}
			}
		}
		return sessInfs;
    }


    /**
     * @Description 踢出用户
     * @Param sessionRegistry
     * @Param user
     * @return void
     * @Author defencez
     * @Date 2024-04-21 11:38
    */
    public static void kickOut(SessionRegistry sessionRegistry,CommonUser<?> user) {
    	
    	//清除会话
    	List<SessionInformation> sessions = getLoginedSessions(sessionRegistry,user);
    	if(null != sessions && sessions.size()>0){
    		for(SessionInformation sessInf:sessions){
    			//让Session失效
    			sessInf.expireNow();
    			//移去Session
    			sessionRegistry.removeSessionInformation(sessInf.getSessionId());
    		}
    	}
    }        
}
